package ai.george.quickstart.controller;


import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@Tag(name = "记忆会话(SpringAI实现)")
@RestController
@RequestMapping("/chat-memory-springai")
public class SpringAIChatMemoryController {


    private final ChatClient memoryChatClient;


    /**
     * 使用构造器注入ChatClient
     *
     * @param chatClientBuilder 由starter自动创建
     */
    public SpringAIChatMemoryController(ChatClient.Builder chatClientBuilder) {
        //公共的chatOptions
        DashScopeChatOptions chatOptions = DashScopeChatOptions.builder()
                .withModel(DashScopeApi.ChatModel.QWEN_PLUS.getValue())
                .withTopP(0.7)
                .build();

        MessageWindowChatMemory chatMemory = MessageWindowChatMemory.builder()
//                .chatMemoryRepository() // 可以指定具体的存储仓库
//                .maxMessages(10) // 设置窗口大小（最大记忆的对话消息数量）
                .build();

        MessageChatMemoryAdvisor chatMemoryAdvisor = MessageChatMemoryAdvisor.builder(chatMemory).build();


        //创建一个 ChatClient（配置了默认的Advisor,直接支持会话记忆功能,不过要使用这个chatClient，需要设置会话id）
        this.memoryChatClient = chatClientBuilder
                .defaultAdvisors(chatMemoryAdvisor)
                .defaultOptions(chatOptions)
                .build();
        System.out.println("SpringAIChatMemoryController初始化");
    }


    @Operation(summary = "ChatMemory", description = "使用SpringAI 官方提供的Advisor实现会话记忆")
    @GetMapping("/spring-memory-advisor")
    public String chatMemory2(@RequestParam(value = "conversationId") @Parameter(name = "conversationId", description = "会话的唯一id") String conversationId,
                              @RequestParam(value = "query") @Parameter(name = "query", description = "请求内容") String query) {
        String content = memoryChatClient
                .prompt()
                .advisors(advisorSpec -> {
                    //可以设置Advisor上下文参数(在后续的Advisor实现类中可以使用)
                    advisorSpec.param(ChatMemory.CONVERSATION_ID, conversationId);
                })
                .user(query)
                .call()
                .content();
        return content;
    }


}
